import tkinter as tk
from tkinter import messagebox
import requests
import os
import time
import subprocess
from win10toast import ToastNotifier
toast = ToastNotifier()
logs = []

cfgpath = " "
cmd = " "

ver = ['20002','2.1Beta']
n1 = "https://gitee.com/summer-uefi/yuanshenqidong-command/raw/master/Beta%E7%89%88%E6%9C%AC%E5%90%88%E9%9B%86/version"
n2 = "https://gitee.com/summer-uefi/yuanshenqidong-command/raw/master/Beta%E7%89%88%E6%9C%AC%E5%90%88%E9%9B%86/version-info"

def qidong(command):
    print('[LOG]尝试启动')
    logs.append("[LOG]尝试启动" + time.asctime())
    subprocess.Popen(command)
    control_panel()
def showinfo_msg(ttll ,msgg ,type):
    me = open("msg.trans.txt",'w')
    k = "t =" + ttll + "\n" + "m =" + msgg
    me.write(k)
    me.close()
    subprocess.Popen("原神启动_Sender.exe")
    if(type == "info"):
        root = tk.Tk()
        root.withdraw()
        tk.messagebox.showinfo(title=ttll,message=msgg)
    if(type == "err"):
        root = tk.Tk()
        root.withdraw()
        tk.messagebox.showerror(title=ttll, message=msgg)
def progquit():
    try:
        cp.destroy()
        cp.quit()
    except:
        window.destroy()
        window.quit()
        quit("用户手动退出|S=1")
    window.destroy()
    window.quit()
    quit('用户手动退出|S=2')

def checkUpdate():
    print('[LOG]检测更新')
    logs.append("[LOG]检测更新"+ time.asctime())
    global v1,v2
    v1 = requests.get(n1)
    # print(v1.text)
    v2 = requests.get(n2)
    # print(v2.text)
    if (ver[0] == v1.text or ver[1] == v2.text):
        return True
    else:
        return False
def cUp():
    rt = checkUpdate()
    if(rt):
        print("[LOG]未发现版本更新。" + "云端版本:" + v1.text + " | " + v2.text)
        logs.append("[LOG]未发现版本更新。" + "云端版本:" + v1.text + " | " + v2.text + " " +time.asctime())
        showinfo_msg("检查更新","未发现版本更新","info")
    else:
        print("[LOG]发现更新！" + v1.text + " | " + v2.text)
        logs.append("[LOG]发现更新！" + v1.text + " | " + v2.text + " " +time.asctime())
        showinfo_msg("检查更新","发现版本更新 " + v1.text + " | " + v2.text + " ,请前往官网下载." ,"info")

def verify():
    try:
        a = open('path.config','r',encoding='utf-8')
        aread = a.readline()
        if('Error' in aread):
            return False
        else:
            return True
    except:
        print("[CSL]请稍等，正在自动获取原神位置。")
        logs.append("[LOG][CSL]获取原神位置 " + " " +time.asctime())
        os.system("start GetLocate.exe")
        time.sleep(1.5)
def whereis():
    a = open('path.config', 'r',encoding='utf-8')
    aread = a.readline()
    print("[LOG]已获取Launcher路径："+aread)
    logs.append("[LOG]已获取Launcher路径："+aread + " " + time.asctime())
    return aread
def readini(cfgpath):
    print('[LOG]Config文件：'+cfgpath)
    logs.append('[LOG]Config文件：'+cfgpath + " " +time.asctime())
    aq = open(cfgpath,'r',encoding='utf-8')
    asq = aq.readlines()
    asq = asq[1]
    return asq

def getL():
    o = verify()
    if (o == False):
        print("[LOG][ERROR]无法读取目录。请联系开发者处理。")
        logs.append("[LOG][ERROR]无法读取目录。请联系开发者处理。")
    else:
        path = whereis()
    global cfgpath
    cfgpath = path + '\\Config.ini'
    aqa = readini(cfgpath)
    aqa = aqa.split('=')
    aqa = aqa[1]
    aqa = aqa.split('\n')
    aqa = aqa[0]
    aqa = aqa + '/YuanShen.exe'
    global cmd
    cmd = '\"' + aqa + '\"'
    print('[LOG]已获取原神路径' + cmd )
    logs.append('[LOG]已获取原神路径' + cmd + " " +time.asctime())
    showinfo_msg("Success","获取路径成功！","info")
    window.destroy()
    mainload(cfgpath ,cmd)
def manual_Get():
    mg = tk.Tk()
    mg.geometry("400x200")
    mg.maxsize(400, 200)
    mg.minsize(400, 200)

def closeY():
    os.system("taskkill /f /im YuanShen.exe")
    print("[LOG]进程结束")
    logs.append("[LOG]进程结束"+ " " +time.asctime())
    showinfo_msg("Success", "原神.exe 已结束！", "info")
def restart():
    os.system("taskkill /f /im YuanShen.exe")
    print("[LOG]进程结束")
    logs.append("[LOG]进程结束" + " " +time.asctime())
    time.sleep(1)
    subprocess.Popen(cmd)
    print("[LOG]正在启动")
    logs.append("[LOG]正在启动" + " " +time.asctime())
def savlog():
    print(logs)
    q = ""
    for i in logs:
        q = q + i +'\n'
    pf = open("log.txt" ,'w')
    pf.write(q)
    pf.close()
def control_panel():
    print('[LOG]控制台启动')
    logs.append("[LOG]控制台启动" + " " +time.asctime())
    showinfo_msg("启动！", "原神，启动！控制台已启动", "info")
    global cp
    cp = tk.Tk()
    cp.geometry("100x250")
    cp.title("Console")
    cp.maxsize(100,250)
    cp.minsize(100,250)
    ysqd = tk.Button(cp, text="原神,关闭！", command=closeY, width=60, height= 3, bg="green")
    ysqd.pack()
    getl = tk.Button(cp, text="重启原神", command=restart, width=60, height= 3, bg="yellow")
    getl.pack()
    btn2 = tk.Button(cp, text="关闭", command=progquit, width=60, height= 3, bg="red")
    btn2.pack()
    btn3 = tk.Button(cp, text="保存LOG", command=savlog(), width=60, height=3, bg="blue")
    btn3.pack()
    while True:
        cp.update()
def start():
    print("[LOG]正在启动")
    logs.append("[LOG]正在启动" + " " +time.asctime())
    try:
        qidong(cmd)
    except:
        showinfo_msg("Err","没有获取路径" ,'err')
        logs.append("[LOG][ERR]没有获取路径")
        showinfo_msg("Err", "获取失败.", "err")
def mainload(a,b):
    global window,txt1,txt2
    window = tk.Tk()
    window.geometry("850x200")
    window.maxsize(850, 200)
    window.minsize(850, 200)
    window.title("原神，启动！" + ver[1])
    txt1 = tk.Label(window, text="CFG路径:" +a, font="微软雅黑" ,fg="green" ,anchor="w")
    txt2 = tk.Label(window, text="原神路径:" +b, font="微软雅黑" ,fg="blue"  ,anchor="w")
    txt1.pack()
    txt2.pack()
    ysqd = tk.Button(window, text="原神,启动！", command=start ,width=60 ,bg ="green")
    ysqd.pack()
    getl = tk.Button(window, text="获取路径", command=getL ,width=60 ,bg ="yellow")
    getl.pack()
    #getm = tk.Button(window, text="手动填写路径", command=manual_Get ,width=60 ,bg ="orange")
    #getm.pack()
    btn1 = tk.Button(window, text="检查更新", command=cUp ,width=60 ,bg ="purple")
    btn1.pack()
    btn2 = tk.Button(window, text="关闭", command=progquit ,width=60 ,bg ="red")
    btn2.pack()
    while True:
        window.update()

if __name__ == "__main__":
    print("[LOG]软件运行")
    showinfo_msg("Hi!","Welcome!","info")
    logs.append("[LOG]软件运行"+ " " +time.asctime())
    mainload(cfgpath,cmd)